﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.IO;
using System.Net;
using System.Threading;
using Movies.CopyUtility;
using System.Security.Permissions;
using System.Security;




namespace Movies
{
    public partial class FormDownloadMovieDetails : Form
    {

        //private ListBox passedFolderList;
        private List<String> passedFolderList;

        public FormDownloadMovieDetails()
        {
            InitializeComponent();
            passedFolderList = HelperDataProvider.getDataStore().getMoviesFolder();

            if (passedFolderList != null)
            {
                foreach (String itemText in passedFolderList)
                {
                    folders.Items.Add(itemText);
                }
            }
        }

        private void cancelButton_Click(object sender, EventArgs e)
        {
            if (downloadThread!=null && downloadThread.IsAlive)
            {
                downloadThread.Abort();
            }
            this.Dispose();
        }


        //bool closeOnEnd = false;

        private Thread downloadThread = null;

        private void startButton_Click(object sender, EventArgs e)
        {
            if (startButton.Text == "Start Downloading")
            {
                int currentHeight = this.Height;
                this.Height = 510;
                this.Top = this.Top - (510 - currentHeight) / 2;

                downlaodResult.Height = 230;
                startButton.Text = "Run in Background";
                
                //this.WindowState = FormWindowState.Maximized;
                downloadThread = new Thread(delegate()
                {
                    processDownlaod();
                });
                downloadThread.Start();
            }
            else if (startButton.Text == "Run in Background")
            {
                if (!isBgProcessAdded)
                {
                    HeplerBGProcesses.addBGProcess(this, progressBar, "Downloading Details", true);
                    isBgProcessAdded = true;
                }
                this.Hide();
        
            }
            else
            {
                this.Dispose();
            }

        }
        private bool isBgProcessAdded = false;

        private void processDownlaod()
        {
            IEnumerator folders = passedFolderList.GetEnumerator();
            while (folders.MoveNext())
            {
                String currentFolder = null;
                if (folders != null && !(currentFolder = folders.Current.ToString().Trim()).Equals(""))
                {
                    processMovieFiles(currentFolder);
                    processMovieFolder(currentFolder);
                }
            }
            callPostDownlaod();
        }

        delegate void postDownlaod();
        private void callPostDownlaod()
        {
            if (progressBar.InvokeRequired)
            {
                postDownlaod d = new postDownlaod(callPostDownlaod);
                WinDisplayControllor.MDIParent.Invoke(d, new object[] { });
            }
            else
            {
                startButton.Text = "Done";
                progressBar.Value = progressBar.Maximum;
                cancelButton.Hide();
                progressBar.Hide();
                statusLabel.Hide();
                HelperDataProvider.getDataStore().scanMoviesDetailsChanges();
            }
        }

        delegate void downlaodRes(String title, String fileName, MovieDetails movieDetails);
        private void updatedDownlaodResult(String title, String fileName, MovieDetails movieDetails)
        {
            if (downlaodResult.InvokeRequired)
            {
                downlaodRes d = new downlaodRes(updatedDownlaodResult);
                WinDisplayControllor.MDIParent.Invoke(d, new object[] { title, fileName, movieDetails});
            }
            else
            {
                int rowIndex = downlaodResult.Rows.Add(new String[] { title, fileName, "Modify Result", "Clear Result" });
                DataGridViewRow row =  downlaodResult.Rows.SharedRow(rowIndex);
                row.Tag = movieDetails;
                if (!stopScrolling.Checked)
                {
                    downlaodResult.FirstDisplayedScrollingRowIndex = rowIndex;
                }
            }
        }


        delegate void SetProgressValue(int val, String src);
        private void updateProgress(int value,String source)
        {
            if (progressBar.InvokeRequired)
            {
                SetProgressValue d = new SetProgressValue(updateProgress);
                WinDisplayControllor.MDIParent.Invoke(d, new object[] { value, source });
            }
            else
            {
                progressBar.Value = Convert.ToInt32(value);
                statusLabel.Text = "Working on: "+source;
            }
        }

        delegate void SetProgressMax(int val);
        private void updateProgressMax(int value)
        {
            if (progressBar.InvokeRequired)
            {
                SetProgressMax d = new SetProgressMax(updateProgressMax);
                WinDisplayControllor.MDIParent.Invoke(d, new object[] { value });
            }
            else
            {
                progressBar.Maximum = Convert.ToInt32(value);
            }
        }



        private void processMovieFiles(String folderSearchLocation)
        {
            if (!folderSearchLocation.Equals("------ Add Folders ------") && !folderSearchLocation.Equals("") && Directory.Exists(folderSearchLocation))
            {
                string[] filePaths = Directory.GetFiles(folderSearchLocation);
                updateProgressMax(filePaths.Length);

                

                int progressVal = 0;
                updateProgress(progressVal, "");
                bool isStoreAtDefault = (HelperSettingProvider.Default().DefaultStore.Trim().Equals("1"));
                    
                foreach (string fileName in filePaths)
                {

                    
                    updateProgress(progressVal, fileName);

                    String actualfileName = fileName.Substring(fileName.LastIndexOf("\\") + 1);
                    String absolutefileName = actualfileName;
                    int dotIndex = absolutefileName.LastIndexOf('.');
                    if (dotIndex > -1 && (dotIndex == (absolutefileName.Length - 4) || dotIndex == (absolutefileName.Length - 5)))
                    {
                        absolutefileName = absolutefileName.Substring(0, dotIndex);
                    }
                    absolutefileName = HelperNameUtil.NormalizeMovieName(absolutefileName);

                    String newFolderLocation = null;
                    if (isStoreAtDefault)
                    {
                        newFolderLocation = HelperSettingProvider.Default().MovieDataStoreLocation + "\\" + absolutefileName;
                    }
                    else
                    {
                        newFolderLocation = folderSearchLocation + "\\" + absolutefileName;
                    }
                    String textForShortcut = "[InternetShortcut]\r\nURL=file:///" + fileName.Replace("\\","/")+"/\r\nIDList=\r\nHotKey=\r\nProp3=";
 
                    if (!Directory.Exists(newFolderLocation))
                    {
                        try
                        {
                            Directory.CreateDirectory(newFolderLocation);
                        }
                        catch (Exception ex)
                        {
                            HelperContentProvider.OmitWarning(ex);
                        }
                    }

                    if (Directory.Exists(newFolderLocation))
                    {
                        if (isCopyMoveEnanbled.Checked && !isStoreAtDefault)
                        {
                            try
                            {
                                File.Move(fileName, newFolderLocation + "\\" + actualfileName);
                            }
                            catch (UnauthorizedAccessException uac)
                            {
                                updateProgress(filePaths.Length, "");
                                MessageBox.Show("Seems You don't have sufficient rights to write to the destination:\n\"" + newFolderLocation + "\"\n\nRestart the Application with Administrator\n1. Right Click on MyMo Icon as installation\n2. Select \"Run as administrator\"", "Access Issue");
                                HelperContentProvider.OmitWarning(uac);
                                return;
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("Problem in accessing the destination:\n\"" + newFolderLocation + "\"", "Access Issue");
                                HelperContentProvider.OmitWarning(ex);
                            }
                        }
                        else
                        {
                            try
                            {
                                File.AppendAllText(newFolderLocation + "\\" + actualfileName + ".url", textForShortcut);
                            }
                            catch (UnauthorizedAccessException uac)
                            {
                                updateProgress(filePaths.Length, "");
                                MessageBox.Show("Seems You don't have sufficient rights to write to the destination:\n\"" + newFolderLocation + "\"\n\nRestart the Application with Administrator\n1. Right Click on MyMo Icon as installation\n2. Select \"Run as administrator\"", "Access Issue");
                                HelperContentProvider.OmitWarning(uac);
                                return;
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("Problem in accessing the destination:\n\"" + newFolderLocation + "\"", "Access Issue");
                                HelperContentProvider.OmitWarning(ex);   
                            }
                            
                        }
                    }
                    progressVal++;
                }
            }
        }


        private void processMovieFolder(String folderSearchLocation)
        {
            if (!folderSearchLocation.Equals("------ Add Folders ------") && !folderSearchLocation.Equals("") && Directory.Exists(folderSearchLocation))
            {
                string[] filePaths = Directory.GetDirectories(folderSearchLocation);
                updateProgressMax(filePaths.Length);
                int progressVal = 0;
                bool isStoreAtDefault = ((HelperSettingProvider.Default().DefaultStore.Trim().Equals("1")) || !HelperFileDetailsGuide.isWriteAllowed(folderSearchLocation));
                String defStoreLocation = HelperSettingProvider.Default().MovieDataStoreLocation;                

                updateProgress(progressVal, "");
                List<String> missingDetailsFor = new List<string>();
                bool createHTML = false;
                bool createCover = false;
                bool createAllAgain = false;

                if (isDownloadCover.Checked)
                {
                    createCover = true;
                }
                if (isDownloadAgain.Checked)
                {
                    createAllAgain = true;
                    createCover = true;
                }

                foreach (string fileNameInDir in filePaths)
                {

                    String fileName = fileNameInDir;
                    
                    updateProgress(progressVal,fileName);
                    String absolutefileName = fileName.Substring(fileName.LastIndexOf("\\") + 1);
                    absolutefileName = HelperNameUtil.NormalizeMovieName(absolutefileName);

                    createHTML=manageExistingFiles(fileName,createCover,createAllAgain);

                    if (isStoreAtDefault)
                    {
                        fileName = defStoreLocation + "\\" + absolutefileName;
                        if (!Directory.Exists(fileName))
                        {
                            Directory.CreateDirectory(fileName);
                        }
                        createHTML = manageExistingFiles(fileName, createCover, createAllAgain);
                    }
                        
                    if(createHTML)
                    {
                        MovieDetails movieDetails = HelperDefaultMovieSelector.GetDefaultMovie(absolutefileName, "0");

                        if (movieDetails == null)
                        {
                            missingDetailsFor.Add(fileName);
                            updatedDownlaodResult("!!!Missing Information!!!", fileName, new MovieDetails(fileName));
                            progressVal++;
                            continue;
                        }
                        if (createCover)
                        {
                            if (movieDetails.ImdbCoverURL != null && !movieDetails.ImdbCoverURL.ToUpper().Equals("N/A"))
                            {
                             
                                movieDetails.SaveToWithImage(fileName);
                                movieDetails.DefSaveWithImage = true;
                            }
                        }
                          
                            movieDetails.SaveTo(fileName);
                        

                        if (isStoreAtDefault)
                        {
                            String textForShortcut = "[InternetShortcut]\r\nURL=file:///" + fileNameInDir.Replace("\\", "/")+"/\r\nIDList=\r\nHotKey=\r\nProp3=";
                            File.AppendAllText(fileName + "\\movie.url", textForShortcut);
                        }
                        updatedDownlaodResult(movieDetails.Name, fileName,movieDetails);
                        progressVal++;
                    }
                    
                }
            }
        }

        private bool manageExistingFiles(String fileName, bool createCover,bool createAllAgain)
        {
            bool createHtml = false;

            if (createAllAgain)
            {
                if (File.Exists(fileName + "\\imdb_cover.jpg"))
                {
                    File.Delete(fileName + "\\imdb_cover.jpg");
                    createHtml = true;
                }
                if (File.Exists(fileName + "\\imdb_details.html"))
                {
                    File.Delete(fileName + "\\imdb_details.html");
                    createHtml = true;
                }
                if (File.Exists(fileName + "\\movie.url"))
                {
                    File.Delete(fileName + "\\movie.url");
                    createHtml = true;
                }

            } else if (!File.Exists(fileName + "\\imdb_cover.jpg") && createCover)
            {
                if (File.Exists(fileName + "\\imdb_details.html"))
                {
                    File.Delete(fileName + "\\imdb_details.html");
                }
                createHtml = true;
            }
            else if (!File.Exists(fileName + "\\imdb_details.html"))
            {
                createHtml = true;
            }
            return createHtml;
        }

        private void ProgressForm_Load(object sender, EventArgs e)
        {
            if (passedFolderList == null || passedFolderList.Count ==0)
            {
                this.Dispose();
                WinDisplayControllor.DisplayDialog("Please add a folder to continue");
            }
            
        }

        private void isDisplayNotFoundEnabled_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void isDownloadAgain_CheckedChanged(object sender, EventArgs e)
        {
            
        }

        private void ProgressForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            WinDisplayControllor.ApplyChangesOnLoadedWin();
        }

        private void downlaodResult_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            DataGridViewRow row = downlaodResult.CurrentRow;
            //row.Selected = true;
            MovieDetails details = (MovieDetails)row.Tag;
            if (details != null)
            {
                FormSelectOrAddMovie disDetails = new FormSelectOrAddMovie(details,details.LoadLocation,false);
                disDetails.ShowDialog();
            }
        }

        private void downlaodResult_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            int selectedRowIndex = int.Parse(e.RowIndex.ToString());

            if (downlaodResult.Columns[e.ColumnIndex] == modifyButton && selectedRowIndex >= 0)
            {
                DataGridViewRow row = downlaodResult.Rows.SharedRow(selectedRowIndex);
                MovieDetails details = (MovieDetails)row.Tag;
                if (details != null)
                {
                    FormSelectOrAddMovie disDetails = new FormSelectOrAddMovie(details, details.LoadLocation,false);
                    MovieDetails detailsModified = disDetails.SelectMovie();
                    if (detailsModified.Name != details.Name)
                    {
                        row.Cells[0].Value = detailsModified.Name;
                    }
                }
            }
            if (downlaodResult.Columns[e.ColumnIndex] == clearSearch && selectedRowIndex >= 0)
            {
                DataGridViewRow row = downlaodResult.Rows.SharedRow(selectedRowIndex);
                MovieDetails details = (MovieDetails)row.Tag;
                details.ClearDetails();
                row.Cells[0].Value = "!!!Missing Information!!!";
            }
        }


    }
}
